package com.niuwa.p2p.service.impl.credit;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Date;

import com.niuwa.p2p.core.constant.StudentCreditEnum;
import com.niuwa.p2p.core.utils.DateUtil;
import com.niuwa.p2p.entity.credit.StudentCreditInfo;
import com.niuwa.p2p.service.credit.NwStudentCreditService;
import com.niuwa.p2p.service.credit.StudentCreditService;

import org.jsoup.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/*
 * 
 * @title 学籍认证方法
 *
 * @author tennyqin
 * @version 1.0
 * @created 2015年4月2日
 */
@Service
public class StudentCreditServiceImpl implements StudentCreditService {

	@Autowired
	private NwStudentCreditService nwStudentCreditService;

	public static final String DATE_FORMAT_YYYY_MM_DD = "yyyy年MM月dd日";

	/**
	 * 学籍认证的方法调用 prama需要 传入验证码和姓名
	 */
	@Override
	public StudentCreditInfo getStudentCredit(String identifyCode,
			String platFromUserNo) {
		StudentCreditInfo studentCreditInfo = null;
		try {
			studentCreditInfo = nwStudentCreditService
					.selectByUserNO(platFromUserNo);
			if (null == studentCreditInfo) {
				studentCreditInfo = getJsoup(identifyCode, platFromUserNo);
				if (null != studentCreditInfo
						&& null != studentCreditInfo.getColgLevel()) {
					nwStudentCreditService.insertCreditInfo(studentCreditInfo);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return studentCreditInfo;
	}

	/**
	 * 正常访问
	 * 
	 * @param vcode
	 * @param name
	 * @return
	 */
	public static StudentCreditInfo getJsoup(String vcode, String platFromUserNo)
			throws Exception {
		if (null == vcode || null == platFromUserNo) {
			return null;
		}
		StudentCreditInfo studentCreditInfo = new StudentCreditInfo();
		studentCreditInfo.setPlatFromUserNo(platFromUserNo);
		studentCreditInfo.setCreatetime(new Date());
		String url = "http://www.chsi.com.cn/xlcx/bg.do?vcode=";
		url = url + vcode + "&srcid=bgcx";
		long start = System.currentTimeMillis();
		Document doc = null;
		int count = 0;
		try {
			doc = Jsoup.connect(url).timeout(5000).get(); // 设置延时5秒
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("Time is:"
					+ (System.currentTimeMillis() - start) + "ms" + "..vcode: "
					+ vcode);
		}
		Element elem = doc.getElementById("fixedPart");
		if (null == elem) { // 无法正常获得
			checkNetStatus(studentCreditInfo, doc);
			return studentCreditInfo;
		}
		Elements elems = elem.getElementsByTag("tr");
		for (Element ele : elems) {
			count++;
			if (count == 1) {
				continue;
			}
			Elements elemsTitles = ele.getElementsByClass("title1");
			Elements elemsCnts = ele.getElementsByClass("cnt1");
			setStudentCreditInfo(studentCreditInfo, elemsTitles, elemsCnts);
		}
		if (null != studentCreditInfo.getColgLevel()
				&& null != studentCreditInfo.getProfessional()) {
			studentCreditInfo.setStudentCreditEnum(StudentCreditEnum.Success);
		}
		return studentCreditInfo;

	}

	/**
	 * 代理访问
	 * 
	 * @param vcode
	 * @param name
	 * @return
	 * @throws Exception
	 */
	public static StudentCreditInfo proxyJsoup(String vcode,
			String platFromUserNo) throws Exception {
		if (null == vcode || null == platFromUserNo) {
			return null;
		}
		StudentCreditInfo studentCreditInfo = new StudentCreditInfo();
		studentCreditInfo.setPlatFromUserNo(platFromUserNo);
		studentCreditInfo.setCreatetime(new Date());
		String urlPath = "http://www.chsi.com.cn/xlcx/bg.do?vcode=";
		urlPath = urlPath + vcode + "&srcid=bgcx";
		URL url = new URL(urlPath);
		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
				"36.250.74.88", 80)); // 代理访问
		HttpURLConnection uc = (HttpURLConnection) url.openConnection(proxy);
		uc.connect();
		String line = null;
		StringBuffer tmp = new StringBuffer();
		BufferedReader in = new BufferedReader(new InputStreamReader(
				uc.getInputStream()));
		while ((line = in.readLine()) != null) {
			tmp.append(line);
		}
		Document doc = Jsoup.parse(String.valueOf(tmp));
		int count = 0;
		Element elem = doc.getElementById("fixedPart");
		if (null == elem) { // 无法正常获得
			checkNetStatus(studentCreditInfo, doc);
			return studentCreditInfo;
		}
		Elements elems = elem.getElementsByTag("tr");
		for (Element ele : elems) {
			count++;
			if (count == 1) {
				continue;
			}
			Elements elemsTitles = ele.getElementsByClass("title1");
			Elements elemsCnts = ele.getElementsByClass("cnt1");
			setStudentCreditInfo(studentCreditInfo, elemsTitles, elemsCnts);
		}
		if (null != studentCreditInfo.getColgLevel()
				&& null != studentCreditInfo.getProfessional()) {
			studentCreditInfo.setStudentCreditEnum(StudentCreditEnum.Success);
		} else {
			studentCreditInfo.setStudentCreditEnum(StudentCreditEnum.Fail);
		}
		return studentCreditInfo;
	}

	private static void setStudentCreditInfo(
			StudentCreditInfo studentCreditInfo, Elements elemsTitles,
			Elements elemsCnts) throws Exception {
		for (int i = 0; i < elemsTitles.size(); i++) {
			if (elemsTitles.get(i).text().equals("性别")) {
				studentCreditInfo.setSex(elemsCnts.get(i).text());
			}
			if (elemsTitles.get(i).text().equals("证件号码")) {
				studentCreditInfo.setDocumentNo(elemsCnts.get(i).text());
			}
			if (elemsTitles.get(i).text().equals("民族")) {
				studentCreditInfo.setNation(elemsCnts.get(i).text());
			}
			if (elemsTitles.get(i).text().equals("出生日期")) {
				studentCreditInfo.setBirth(DateUtil.parseStringToDate(elemsCnts
						.get(i).text(), DATE_FORMAT_YYYY_MM_DD));
			}
			if (elemsTitles.get(i).text().equals("院校")) {
				studentCreditInfo.setCollege(elemsCnts.get(i).text());
			}
			if (elemsTitles.get(i).text().equals("层次")) {
				studentCreditInfo.setColgLevel(elemsCnts.get(i).text());
			}
			if (elemsTitles.get(i).text().equals("院系")) {
				studentCreditInfo.setFaculty(elemsCnts.get(i).text());
			}
			if (elemsTitles.get(i).text().equals("班级")) {
				studentCreditInfo.setClasses(elemsCnts.get(i).text());
			}
			if (elemsTitles.get(i).text().equals("专业")) {
				studentCreditInfo.setProfessional(elemsCnts.get(i).text());
			}
			if (elemsTitles.get(i).text().equals("学号")) {
				studentCreditInfo.setStudentId(elemsCnts.get(i).text());
			}
			if (elemsTitles.get(i).text().equals("形式")) {
				studentCreditInfo.setModality(elemsCnts.get(i).text());
			}
			if (elemsTitles.get(i).text().equals("入学时间")) {
				studentCreditInfo.setEntranceTime(DateUtil.parseStringToDate(
						elemsCnts.get(i).text(), DATE_FORMAT_YYYY_MM_DD));
			}
			if (elemsTitles.get(i).text().equals("学制")) {
				studentCreditInfo.setEducational(elemsCnts.get(i).text());
			}
			if (elemsTitles.get(i).text().equals("类型")) {
				studentCreditInfo.setType(elemsCnts.get(i).text());
			}
			if (elemsTitles.get(i).text().equals("学籍状态")) {
				studentCreditInfo.setStatus(elemsCnts.get(i).text());
			}
		}

	}

	private static void checkNetStatus(StudentCreditInfo studentCreditInfo,
			Document doc) {
		Element elem = doc.getElementById("msgDiv");
		if (null != elem) {
			if (null != elem.text()) {
				if (elem.text().indexOf("不合要求的在线验证码") > -1) {
					studentCreditInfo
							.setStudentCreditEnum(StudentCreditEnum.Fail);
				}
				if (elem.text().indexOf("访问系统过于频繁") > -1) {
					studentCreditInfo
							.setStudentCreditEnum(StudentCreditEnum.Net);
				}
			}
		} else {
			studentCreditInfo.setStudentCreditEnum(StudentCreditEnum.Other);
		}
	}

	public static void main(String[] args) throws Exception {
		/*
		 * while (true) { try { Thread.sleep(1000 * 2); getJsoup(); } catch
		 * (Exception e) { } }
		 */
		// String vcode = "963297572188";
		// String name = "秦亮";
		// proxyJsoup(vcode, name);
		// StudentCreditInfo studentCreditInfo = getJsoup(vcode, name);
		// StudentCreditInfo studentCreditInfo = proxyJsoup(vcode, name);
		String dateStr = "1995年2月18日";
		System.out.println(DateUtil.parseStringToDate(dateStr,
				DATE_FORMAT_YYYY_MM_DD));
	}

}
